package com.yz.fanrenmianshi.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yz.fanrenmianshi.common.ErrorCode;
import com.yz.fanrenmianshi.constant.CommonConstant;
import com.yz.fanrenmianshi.exception.ThrowUtils;
import com.yz.fanrenmianshi.mapper.QuestionFavourMapper;
import com.yz.fanrenmianshi.model.dto.questionfavour.QuestionFavourQueryRequest;
import com.yz.fanrenmianshi.model.entity.Question;
import com.yz.fanrenmianshi.model.entity.QuestionFavour;
import com.yz.fanrenmianshi.model.entity.User;
import com.yz.fanrenmianshi.model.vo.QuestionFavourVO;
import com.yz.fanrenmianshi.model.vo.QuestionVO;
import com.yz.fanrenmianshi.model.vo.UserVO;
import com.yz.fanrenmianshi.service.QuestionFavourService;
import com.yz.fanrenmianshi.service.QuestionService;
import com.yz.fanrenmianshi.service.UserService;
import com.yz.fanrenmianshi.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 题目收藏服务实现
 *
 */
@Service
@Slf4j
public class QuestionFavourServiceImpl extends ServiceImpl<QuestionFavourMapper, QuestionFavour> implements QuestionFavourService {

    @Resource
    private UserService userService;

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionFavourMapper questionFavourMapper;

    /**
     * 校验数据
     *
     * @param questionFavour
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validQuestionFavour(QuestionFavour questionFavour, boolean add) {
        ThrowUtils.throwIf(questionFavour == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long questionId = questionFavour.getQuestionId();
        Long userId = questionFavour.getUserId();
        // 创建数据时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(questionId == null || questionId <= 0, ErrorCode.PARAMS_ERROR, "题目id不能为空");
            ThrowUtils.throwIf(userId == null || userId <= 0, ErrorCode.PARAMS_ERROR, "用户id不能为空");
        }
        // 修改数据时，有参数则校验
        if (questionId != null) {
            ThrowUtils.throwIf(questionId <= 0, ErrorCode.PARAMS_ERROR, "题目id不能小于等于0");
        }
        if (userId != null) {
            ThrowUtils.throwIf(userId <= 0, ErrorCode.PARAMS_ERROR, "用户id不能小于等于0");
        }
    }

    /**
     * 获取查询条件
     *
     * @param questionFavourQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionFavour> getQueryWrapper(QuestionFavourQueryRequest questionFavourQueryRequest) {
        QueryWrapper<QuestionFavour> queryWrapper = new QueryWrapper<>();
        if (questionFavourQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = questionFavourQueryRequest.getId();
        Long notId = questionFavourQueryRequest.getNotId();
        Long questionId = questionFavourQueryRequest.getQuestionId();
        Long userId = questionFavourQueryRequest.getUserId();
        String sortField = questionFavourQueryRequest.getSortField();
        String sortOrder = questionFavourQueryRequest.getSortOrder();

        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);

        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取题目收藏封装
     *
     * @param questionFavour
     * @param request
     * @return
     */
    @Override
    public QuestionFavourVO getQuestionFavourVO(QuestionFavour questionFavour, HttpServletRequest request) {
        // 对象转封装类
        QuestionFavourVO questionFavourVO = QuestionFavourVO.objToVo(questionFavour);

        // 关联查询用户信息
        Long userId = questionFavour.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        questionFavourVO.setUser(userVO);

        return questionFavourVO;
    }

    /**
     * 分页获取题目收藏封装
     *
     * @param questionFavourPage
     * @param request
     * @return
     */
    @Override
    public Page<QuestionFavourVO> getQuestionFavourVOPage(Page<QuestionFavour> questionFavourPage, HttpServletRequest request) {
        List<QuestionFavour> questionFavourList = questionFavourPage.getRecords();
        Page<QuestionFavourVO> questionFavourVOPage = new Page<>(questionFavourPage.getCurrent(), questionFavourPage.getSize(), questionFavourPage.getTotal());
        if (CollUtil.isEmpty(questionFavourList)) {
            return questionFavourVOPage;
        }
        // 对象列表 => 封装对象列表
        List<QuestionFavourVO> questionFavourVOList = questionFavourList.stream().map(questionFavour -> {
            return QuestionFavourVO.objToVo(questionFavour);
        }).collect(Collectors.toList());

        // 关联查询用户信息
        Set<Long> userIdSet = questionFavourList.stream().map(QuestionFavour::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        // 关联查询题目信息
        Set<Long> questionIdSet = questionFavourList.stream().map(QuestionFavour::getQuestionId).collect(Collectors.toSet());
        Map<Long, List<Question>> questionIdQuestionListMap = questionService.listByIds(questionIdSet).stream()
                .collect(Collectors.groupingBy(Question::getId));

        // 填充用户信息和题目信息
        questionFavourVOList.forEach(questionFavourVO -> {
            Long userId = questionFavourVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionFavourVO.setUser(userService.getUserVO(user));

            Long questionId = questionFavourVO.getQuestionId();
            Question question = null;
            if (questionIdQuestionListMap.containsKey(questionId)) {
                question = questionIdQuestionListMap.get(questionId).get(0);
            }
            if (question != null) {
                QuestionVO questionVO = new QuestionVO();
                BeanUtils.copyProperties(question, questionVO);
                questionFavourVO.setQuestion(questionVO);
            }
        });

        questionFavourVOPage.setRecords(questionFavourVOList);
        return questionFavourVOPage;
    }

    @Override
    public QuestionFavour listDeletedFavour(Long questionId, Long userId) {
        return questionFavourMapper.listDeletedFavour(questionId, userId);
    }

    @Override
    public boolean restoreDeletedFavour(Long id) {
        Date updateTime = new Date();
        return questionFavourMapper.restoreDeletedFavour(id, updateTime) > 0;
    }

    @Override
    public boolean deleteQuestionFavour(Long id) {
        Date updateTime = new Date();
        return questionFavourMapper.deleteFavour(id, updateTime) > 0;
    }


}